<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <el-form>
      <el-form-item>
        <el-button type="primary" @click="submitForm"> 保存 </el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button @click="handleAddOption">添加字段选项</el-button>
        <el-button @click="handleDeleteOption">删除字段选项</el-button>
      </el-form-item>
    </el-form>
    <el-form
      v-loading="formLoading"
      :model="formData"
      ref="formRef"
      :rules="formRules"
      label-width="auto"
      style="display: flex"
    >
      <el-form-item label="字段名称" prop="showName" style="margin-right: 30px">
        <el-input
          v-model="formData.showName"
          placeholder="请输入字段名称"
          :clearable="true"
          type="text"
          :disabled="!formData.isEditName"
        />
      </el-form-item>

      <el-form-item label="是否必填" prop="isMustFill" style="margin-right: 30px">
        <el-checkbox v-model="formData.isMustFill" :disabled="!formData.isEditMustFill" />
      </el-form-item>

      <el-form-item label="是否显示" prop="isShow">
        <el-checkbox v-model="formData.isShow" :disabled="!formData.isEditShow" />
      </el-form-item>
    </el-form>
    <Table
      :columns="columns"
      :adaptive="true"
      :data="formData.options"
      :row-style="rowStyle"
      @row-click="handleRowClick"
      class="option-manage"
    >
      <template #sort>
        <div class="flex items-center">
          <Icon
            icon="material-symbols:drag-pan"
            data-inline="false"
            class="drag-option cursor-grab"
            @mouseenter="rowDrop()"
            style="margin-left: 10px"
          />
        </div>
      </template>
      <template #name="{ row }">
        <el-input v-model="row.name" style="width: 90%" input-style="text-align: center" />
      </template>

      <template #isDisabled="{ row }">
        <el-checkbox v-model="row.isDisabled" />
      </template>
    </Table>
  </Dialog>
</template>
<script setup name="BusinessFieldEdit" lang="ts">
import * as businessFieldApi from '@/api/setting/businessField'
import Sortable from 'sortablejs'

const dialogTitle = ref('')
const dialogVisible = ref(false)
const formRef = ref()
const formLoading = ref(false)
const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const formData = ref({
  id: undefined,
  showName: undefined,
  isMustFill: undefined,
  isEditName: undefined,
  isShow: undefined,
  isEditMustFill: undefined,
  isEditShow: undefined,
  options: [] as any[]
})
const formRules = reactive({
  showName: [{ required: true, message: '请输入显示字段名称', trigger: 'change' }]
})
const tableCurrentRow = ref()
const columns = [
  {
    label: '排序',
    prop: 'sort',
    width: '40px',
    slot: 'sort'
  },
  {
    label: '选项名称',
    prop: 'name',
    slot: 'name'
  },

  {
    label: '是否停用',
    prop: 'isDisabled',
    width: '240px',
    slot: 'isDisabled'
  }
]
let currentMaxOptionId = 0
/** 打开弹窗 */
const open = async (id) => {
  formLoading.value = true
  try {
    formData.value = await businessFieldApi.singleGet(id)
    formData.value.options.forEach((option) => {
      if (option.id > currentMaxOptionId) currentMaxOptionId = option.id
    })
  } finally {
    formLoading.value = false
  }

  dialogVisible.value = true
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

const emit = defineEmits(['success'])
/** 提交表单 */
const submitForm = async () => {
  await businessFieldApi.update(formData.value)
  message.success(t('common.updateSuccess'))
  dialogVisible.value = false
  emit('success')
}

/** table行的style的回调方法 */
const rowStyle = ({ row }) => {
  if (row?.operateType == 'delete') {
    return { display: 'none' }
  } else return {}
}

/** table行点击事件 */
const handleRowClick = (row) => {
  tableCurrentRow.value = row
}

const handleAddOption = () => {
  const data = {
    id: ++currentMaxOptionId,
    businessFieldId: formData.value.id,
    name: '',
    isDisabled: false,
    operateType: 'new'
  }

  formData.value.options.push(data)
}

const handleDeleteOption = () => {
  if (tableCurrentRow.value === undefined) {
    message.alertError('请选择要删除的字段选项')
    return
  }

  tableCurrentRow.value.operateType = 'delete'
}

const rowDrop = () => {
  nextTick(() => {
    const wrapper: HTMLElement | null = document.querySelector(
      '.option-manage .el-table__body-wrapper tbody'
    )
    Sortable.create(wrapper, {
      animation: 300,
      handle: '.drag-option',
      onEnd: async ({ newIndex, oldIndex }) => {
        const currentRow = formData.value.options.splice(oldIndex, 1)[0]
        formData.value.options.splice(newIndex, 0, currentRow)
      }
    })
  })
}
</script>
